// 使用uart进行通信，同时使用两个uart串口，一个用于接收数据，另一个用于发送数据，实现数据转发。

#include <stdio.h>
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "driver/gpio.h"
#include "driver/uart.h"

// 定义uart1
#define Baud_rate_1 (9600)
#define uart_num_1 UART_NUM_1
#define uart_tx_pin_num_1 GPIO_NUM_12
#define uart_rx_pin_num_1 GPIO_NUM_13
#define uart_rxbuffer_size_1 (1024)
#define uart_txbuffer_size_1 (1024)
static uint8_t uart_buffer_1[1024];

// 定义uart2
#define Baud_rate_2 (9600)
#define uart_num_2 UART_NUM_2
#define uart_tx_pin_num_2 GPIO_NUM_2
#define uart_rx_pin_num_2 GPIO_NUM_15
#define uart_rxbuffer_size_2 (1024)
#define uart_txbuffer_size_2 (1024)
static uint8_t uart_buffer_2[1024];



void app_main(void)
{

    uart_config_t uart_config_1 = {
        .baud_rate = Baud_rate_1,
        .data_bits = UART_DATA_8_BITS,
        .flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
        .parity = UART_PARITY_DISABLE,
        .stop_bits = UART_STOP_BITS_1,
        .source_clk = UART_SCLK_DEFAULT
    };

    uart_config_t uart_config_2 = {
        .baud_rate = Baud_rate_2,
        .data_bits = UART_DATA_8_BITS,
        .flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
        .parity = UART_PARITY_DISABLE,
        .stop_bits = UART_STOP_BITS_1,
        .source_clk = UART_SCLK_DEFAULT
    };

    uart_param_config(uart_num_1,&uart_config_1);

    uart_param_config(uart_num_2,&uart_config_2);

    uart_set_pin(uart_num_1,uart_tx_pin_num_1,uart_rx_pin_num_1 ,-1,-1);

    uart_set_pin(uart_num_2,uart_tx_pin_num_2,uart_rx_pin_num_2 ,-1,-1);

    uart_driver_install(uart_num_1,uart_rxbuffer_size_1,uart_txbuffer_size_1,0,NULL,0);

    uart_driver_install(uart_num_2,uart_rxbuffer_size_2,uart_txbuffer_size_2,0,NULL,0);


    while (1)
    {
        int rec = uart_read_bytes(uart_num_2,uart_buffer_2,1024,pdMS_TO_TICKS(300));
        if (rec)
        {   
            char str[rec + 1];
            for (size_t i = 0; i < rec; i++) {
                str[i] = (char)uart_buffer_2[i];
            }
            str[rec] = '\0';   
            ESP_LOGI("UART","GAT MSG : %s\n",str);
            uart_write_bytes(uart_num_1,uart_buffer_2,rec);
        }
    }
}

